package com.husky.easyexcle.controller;

import com.alibaba.excel.EasyExcel;
import com.husky.easyexcle.entity.ExcelDateEntity;
import com.husky.easyexcle.entity.WriteExcelBasicEntity;
import com.husky.easyexcle.service.ExcelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author husky
 * @Date 2022/3/22 15:58
 * @Description: Excel相关控制层
 **/

@RestController
@Slf4j
public class ExcelController {

    @Autowired
    private ExcelService excelServiceImpl;
    /**
     * 读取上传Excel数据
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("read/excel/data")
    public String readExcelData(MultipartFile file) {
        log.info("读取上传Excel开始。file={}",file);
      try {
          List<ExcelDateEntity> list = excelServiceImpl.readExcelData(file);
          log.info("list={}",list);
          return "SUCCESS";
      }catch (Exception e){
          log.error("读取上传Excel异常。Exception={}",e);
          return "FAIL";
      }

    }

    /**
     * 下载Excel
     * @param response
     * @throws IOException
     */
    @GetMapping("download/excel")
    public void download(HttpServletResponse response) {
        try {
            //官方： 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            //官方：  这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("下载Excel的文件名", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            List<WriteExcelBasicEntity> dataList = new CopyOnWriteArrayList<>();
            for(int i=1;i<100;i++){
                WriteExcelBasicEntity w = new WriteExcelBasicEntity();
                w.setStringData("字符串"+i);
                w.setDateData(LocalDateTime.now().plusMinutes(i));
                w.setDoubleData(new Random().nextInt(1000));
                dataList.add(w);
            }
            EasyExcel.write(response.getOutputStream(), WriteExcelBasicEntity.class).sheet("基础下载模板").doWrite(dataList);
        }catch (Exception e){
            log.error("读取上传Excel异常。Exception={}",e);
        }

    }

}
